package com.situ.hospital.servlet;

import com.situ.hospital.pojo.Auth;
import com.situ.hospital.pojo.Department;
import com.situ.hospital.pojo.User;
import com.situ.hospital.pojo.query.UserQuery;
import com.situ.hospital.pojo.vo.UserVO;
import com.situ.hospital.service.IAuthService;
import com.situ.hospital.service.IDepartmentService;
import com.situ.hospital.service.IUserService;
import com.situ.hospital.service.impl.AuthServiceImpl;
import com.situ.hospital.service.impl.DepartmentServiceImpl;
import com.situ.hospital.service.impl.UserServiceImpl;
import com.situ.hospital.util.*;
import org.springframework.util.ObjectUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/user")
public class UserServlet extends HttpServlet {

    private IUserService userService = new UserServiceImpl();
    private IAuthService authService = new AuthServiceImpl();
    private IDepartmentService departmentService = new DepartmentServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        switch (method) {
            case "selectByPage":
                selectByPage(req,resp);
                break;
            case "deleteById":
                deleteById(req,resp);
                break;
            case "deleteAll":
                deleteAll(req,resp);
                break;
            case "add":
                add(req,resp);
                break;
            case "selectMap":
                selectMap(req,resp);
                break;
            case "update":
                update(req,resp);
                break;
            case "updateStatus":
                updateStatus(req,resp);
                break;
            case "login":
                login(req,resp);
                break;
            case "logout":
                logout(req,resp);
                break;
            case "selectUser":
                selectUser(req,resp);
                break;
        }
    }

    private void selectUser(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("UserServlet.selectUser");
        List<User> list = userService.selectUser();
        JSONUtil.toJSON(resp, list);
    }

    private void logout(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("UserServlet.logout");
        HttpSession session = req.getSession();
        session.removeAttribute("user");
        session.removeAttribute("auths");
        Cookie cookie = CookieUtils.getCookie(req,"autoLogin");
        if (cookie != null) {
            cookie.setMaxAge(0);
            resp.addCookie(cookie);
        }
        JSONUtil.toJSON(resp,Result.ok("退出成功"));
    }

    private void login(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("UserServlet.login");
        String name = req.getParameter("name");
        String password = req.getParameter("password");
        String code = req.getParameter("code");
        HttpSession session = req.getSession();
        String codeInSession = (String) session.getAttribute("codeInSession");

        if(!codeInSession.equalsIgnoreCase(code)) {
            JSONUtil.toJSON(resp, Result.error("验证码错误"));
            return;
        }

        User user = userService.login(name, password);

        if(user == null) {
            JSONUtil.toJSON(resp,Result.error("账号或密码错误"));
            return;
        }

        if(user.getStatus() == 0) {
            JSONUtil.toJSON(resp,Result.error("该账号已停用"));
            return;
        }

        String autoLogin = req.getParameter("autoLogin");
        if(!ObjectUtils.isEmpty(autoLogin)) {
            Cookie cookie = new Cookie("autoLogin",user.getName() + "&" + user.getPassword());
            cookie.setMaxAge(60*60*24*7);
            cookie.setPath(req.getContextPath());
            resp.addCookie(cookie);
        }

        session.setAttribute("user",user);
        List<Auth> authList = authService.selectByRole(user.getRole());
        session.setAttribute("authList", authList);
        JSONUtil.toJSON(resp,Result.ok("登录成功"));
    }

    private void updateStatus(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("UserServlet.updateStatus");
        String id = req.getParameter("id");
        String status = req.getParameter("status");
        userService.updateStatus(Integer.parseInt(id), Integer.parseInt(status));
        JSONUtil.toJSON(resp, Result.ok("更新成功"));
    }

    private void update(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("UserServlet.update");
        User user = MyBeanUtil.copyToBean(req, User.class);
        userService.update(user);
        JSONUtil.toJSON(resp, Result.ok("更新成功"));
    }

    private void selectMap(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("UserServlet.selectById");
        String id = req.getParameter("id");
        User user = userService.selectById(Integer.parseInt(id));
        List<Department> list = departmentService.selectAll();
        Map<String,Object> map = new HashMap<>();
        map.put("user",user);
        map.put("department",list);
        JSONUtil.toJSON(resp, Result.ok(map));
    }

    private void add(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("UserServlet.add");
        User user = MyBeanUtil.copyToBean(req, User.class);
        userService.add(user);
        JSONUtil.toJSON(resp, Result.ok("添加成功"));
    }

    private void deleteAll(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("UserServlet.deleteAll");
        String[] ids = req.getParameterValues("ids[]");
        userService.deleteAll(ids);
        JSONUtil.toJSON(resp, Result.ok("删除成功"));
    }

    private void deleteById(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("UserServlet.deleteById");
        String id = req.getParameter("id");
        userService.deleteById(Integer.parseInt(id));
        JSONUtil.toJSON(resp, Result.ok("删除成功"));
    }

    private void selectByPage(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("UserServlet.selectByPage");
        UserQuery userQuery = MyBeanUtil.copyToBean(req, UserQuery.class);
        PageResult<UserVO> pageResult = userService.selectByPage(userQuery);
        JSONUtil.toJSON(resp, pageResult);
    }
}
